package com.project.application.framework.security.service;

import com.project.application.common.exception.ServiceException;
import com.project.application.framework.config.AppConfig;
import com.project.application.framework.security.LoginBody;
import com.project.application.framework.security.LoginUser;
import com.project.application.server.system.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author levnli
 */
@Component
@Slf4j
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private CaptchaService captchaService;


    /**
     * 登录验证
     *
     * @param loginBody 登录
     * @return 结果
     */
    public String login(LoginBody loginBody) {
        boolean captchaOnOff = AppConfig.getCaptcha();
         // 验证码开关
        if (captchaOnOff) {
            captchaService.validateCaptcha(loginBody.getCode(), loginBody.getUuid());
        }
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new ServiceException("密码错误");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
